﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.WindowsDesktopEx.Base;

namespace WinFormApp
{
    public partial class FTestSemaphore : Form
    {
        public FTestSemaphore()
        {
            InitializeComponent();
        }

        private Semaphore _semaphoreMaxClients = null;
        private void FTestSemaphore_Load(object sender, EventArgs e)
        {
            int maxConnections = 2;
            this._semaphoreMaxClients = new Semaphore(maxConnections, maxConnections);

            Task.Factory.StartNew(Test);
        }

        private void Test()
        {
            int timeout = 10000;
            bool result1 = this._semaphoreMaxClients.WaitOne(timeout);
            bool result2 = this._semaphoreMaxClients.WaitOne(timeout);

            try
            {
                bool result3 = this._semaphoreMaxClients.WaitOne(timeout);

                bool result4 = this._semaphoreMaxClients.WaitOne(timeout);
            }
            catch (Exception ex)
            {
                var windows = WindowHelper.FindWindows(t => t.Title.Contains("Microsoft Visual C++ Runtime Library"));
                Loger.Warn(ex);
            }
        }

        private void btnDispose_Click(object sender, EventArgs e)
        {
            this._semaphoreMaxClients.Close();
            this._semaphoreMaxClients.Dispose();
        }
    }
}
